package com.example.obtaingaode.activity;

import android.content.DialogInterface;
import android.graphics.Canvas;
import android.os.Build;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseItemDraggableAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback;
import com.chad.library.adapter.base.listener.OnItemDragListener;
import com.chad.library.adapter.base.listener.OnItemSwipeListener;
import com.example.obtaingaode.R;
import com.example.obtaingaode.bean.CommonBean;
import com.example.obtaingaode.db.DbEntity;
import com.example.obtaingaode.db.DbEntity_;
import com.example.obtaingaode.di.ActivityComponent;
import com.example.obtaingaode.di.DaggerActivityComponent;
import com.example.obtaingaode.net.MApi;
import com.example.obtaingaode.util.Constants;
import com.example.obtaingaode.util.HintUtil;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import frame.m.com.mylibrary.http.BaseResult;
import frame.m.com.mylibrary.http.HttpUtil;
import frame.m.com.mylibrary.http.ProgressSubscriber;
import io.objectbox.Box;
import io.objectbox.query.QueryBuilder;
import io.reactivex.Observable;
import io.reactivex.subjects.PublishSubject;

public class ShowDbActivity extends AppCompatActivity implements BaseQuickAdapter
        .OnItemClickListener, BaseQuickAdapter.UpFetchListener, SwipeRefreshLayout
        .OnRefreshListener {
    RecyclerView rvMain;
    List<DbEntity> mDatas=new ArrayList<>();

    @Inject
    Box<DbEntity> dbEntityBox;
    MyAdapter myAdapter;
    @Inject
    MApi mApi;
    @Inject
    HttpUtil mHttpUtil;
    QMUIDialog mDialog;
    ImageView ivBack;
    SwipeRefreshLayout srMain;

    public final PublishSubject<ActivityEvent> lifecycleCallbacksPublishSubject = PublishSubject
            .create();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_db);
        DaggerActivityComponent.builder().appComponent(MyApplication.getAppComponent()).build().inject(this);
        initView();
        initAdapter();
    }

    OnItemDragListener onItemDragListener = new OnItemDragListener() {
        @Override
        public void onItemDragStart(RecyclerView.ViewHolder viewHolder, int pos){}
        @Override
        public void onItemDragMoving(RecyclerView.ViewHolder source, int from, RecyclerView.ViewHolder target, int to) {}
        @Override
        public void onItemDragEnd(RecyclerView.ViewHolder viewHolder, int pos) {
            Logger.d("准备删除"+myAdapter.getItem(pos).getId()+"这一项");
            dbEntityBox.remove(myAdapter.getItem(pos).getId());
        }
    };
    OnItemSwipeListener onItemSwipeListener = new OnItemSwipeListener() {
        @Override
        public void onItemSwipeStart(RecyclerView.ViewHolder viewHolder, int pos) {}
        @Override
        public void clearView(RecyclerView.ViewHolder viewHolder, int pos) {}
        @Override
        public void onItemSwiped(RecyclerView.ViewHolder viewHolder, int pos) {
            Logger.d("准备删除"+myAdapter.getItem(pos).getId()+"这一项");
            dbEntityBox.remove(myAdapter.getItem(pos).getId());
        }

        @Override
        public void onItemSwipeMoving(Canvas canvas, RecyclerView.ViewHolder viewHolder, float
                dX, float dY, boolean isCurrentlyActive) {

        }
    };





    private void initAdapter() {
        rvMain.setLayoutManager(new LinearLayoutManager(this));
        myAdapter=new MyAdapter(mDatas);
        ItemDragAndSwipeCallback itemDragAndSwipeCallback=new ItemDragAndSwipeCallback(myAdapter);
        ItemTouchHelper itemtouchHelper=new ItemTouchHelper(itemDragAndSwipeCallback);
        itemtouchHelper.attachToRecyclerView(rvMain);
        // 开启拖拽
        myAdapter.enableDragItem(itemtouchHelper,R.id.fl_item_main,true);
        myAdapter.setOnItemDragListener(onItemDragListener);
        myAdapter.setUpFetchEnable(true);

        // 开启滑动删除
        myAdapter.enableSwipeItem();
        myAdapter.setOnItemSwipeListener(onItemSwipeListener);
        myAdapter.setOnItemClickListener(this);

        rvMain.setAdapter(myAdapter);
        mDatas.addAll(dbEntityBox.getAll());
        Logger.d(new Gson().toJson(dbEntityBox.getAll()));
        myAdapter.setNewData(mDatas);
    }

    private void refreshData(){
        myAdapter.setNewData(dbEntityBox.query().order(DbEntity_.id, QueryBuilder.DESCENDING).build().find());
        srMain.setRefreshing(false);
    }

    private void initView() {
        rvMain= (RecyclerView) findViewById(R.id.rv_main);
        ivBack= (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        srMain= (SwipeRefreshLayout) findViewById(R.id.sw_main);
        srMain.setOnRefreshListener(this);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
       final DbEntity dbEntity= (DbEntity) adapter.getItem(position);
        String[] items=new String[]{"上传该条记录","删除该条记录","变更类型为已上传"};
        mDialog= new QMUIDialog.MenuDialogBuilder(this).addItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if(i==0)
                {
                    if(dbEntity.getIsSaveNet())
                    {
                        HintUtil.showErrorStr("该条记录已上传,无需重复上传");
                        return;
                    }
                    dismissMDialog();
                    requestDbentrty(dbEntity);
                }else if(i==1){
                    dismissMDialog();
                    if (!dbEntity.getIsSaveNet()){
                        HintUtil.showErrorStr("该记录尚未上传,不能删除");
                    }else {
                        dbEntityBox.remove(dbEntity.getId());
                        refreshData();
                        HintUtil.showSuccessStr("删除成功");
                    }
                }else if(i==2)
                {
                    dismissMDialog();
                    HintUtil.showErrorStr("该功能尚未实现!");

                }
            }
        }).create();
        mDialog.show();
    }

    private void dismissMDialog() {
        if(mDialog!=null)
        {
            mDialog.dismiss();
        }
    }

    private void requestDbentrty(final DbEntity dbEntity) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("actionName", Constants.URL_SAVE);
        map.put("positionData", dbEntity.getLocation());
        map.put("deviceType", dbEntity.getDeviceType());
        map.put("deviceNo", dbEntity.getDeviceNo());
        map.put("remark", dbEntity.getRemark());
        map.put("userNo", dbEntity.getUserNo());
        String url = String.format("%s?para=%s", Constants.getBaseUrl(), new Gson()
                .toJson(map).toString());
        Observable<BaseResult<String>> ob = mApi
                .save(url);
        mHttpUtil.toSubcribe(ob, new ProgressSubscriber<String>(ShowDbActivity
                .this) {
            @Override
            protected void _onNext(String o) {
                HintUtil.showSuccessStr(ShowDbActivity.this, "保存成功");
                updateAleady(dbEntity.getId());
                refreshData();
            }
        }, ActivityEvent.PAUSE, lifecycleCallbacksPublishSubject);
    }

    private void updateAleady(long putId) {
        List<DbEntity> dbEntities = dbEntityBox.query().equal(DbEntity_.id, putId).build().find();
        if (dbEntities.isEmpty()) {
            return;
        }
        DbEntity dbEntity = dbEntities.get(0);
        dbEntity.setSaveNet(true);
        dbEntityBox.put(dbEntity);
    }

    @Override
    public void onUpFetch() {
        refreshData();
    }

    @Override
    public void onRefresh() {
        refreshData();
    }


    public class MyAdapter extends BaseItemDraggableAdapter<DbEntity,BaseViewHolder> {

        public MyAdapter( @Nullable List<DbEntity> data) {
            super(R.layout.view_item, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, DbEntity item) {
                helper.setText(R.id.tv_id,""+item.getId())
                        .setText(R.id.tv_type_id,item.getDeviceNo())
                        .setText(R.id.tv_type_name,item.getRemark())
                        .setText(R.id.tv_location,item.getLocation())
                        .setText(R.id.tv_user_no,item.getUserNo());
            ((TextView) helper.getView(R.id.tv_tag)).setText(item.getIsSaveNet()?"已上传":"未上传");
            helper.getView(R.id.tv_tag).setBackgroundResource(item.getIsSaveNet()?R.drawable.shape_back_red_border_red_round:R.drawable.shape_back_black_border_black_round);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                ((TextView) helper.getView(R.id.tv_tag)).setTextAppearance(item.getIsSaveNet()?R.style.TagOk:R.style.TagError);
            }else{
                ((TextView) helper.getView(R.id.tv_tag)).setTextAppearance(mContext,item.getIsSaveNet()?R.style.TagOk:R.style.TagError);
            }
        }
    }


}
